package com.example.data.factory.common.configer;

import com.example.data.factory.common.Exception.CommonErrorCode;
import com.example.data.factory.common.Exception.MyException;
import com.example.data.factory.common.result.ResultBase;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@Slf4j
public class MyExceptionController {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    @ExceptionHandler(MyException.class)
    public ResponseEntity<Map<String, Object>> handleException(MyException ex, HttpServletRequest request) {
        return errorResult(ex.getMessage(), CommonErrorCode.BUSINESS_ERROR);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleException(Exception e, HttpServletRequest request) {
        return errorResult(e.getMessage(), CommonErrorCode.UNKNOWN_ERROR);
    }

    private ResponseEntity<Map<String, Object>> errorResult(String messageStr, CommonErrorCode errorCode) {
        log.warn("业务异常：{}", messageStr);

        ResultBase resultBase = ResultBase.fail();
        resultBase.setMessage(messageStr);
        resultBase.setCode(errorCode);

        Map<String, Object> responseBody = new HashMap<>();
        responseBody.put("code", resultBase.getCode());
        responseBody.put("message", resultBase.getMessage());
        responseBody.put("success", false); // 根据您的ResultBase类调整此部分

        return new ResponseEntity<>(responseBody, HttpStatus.valueOf(errorCode.getHttpStatus ()));
    }
}